import util.ListNode;

import java.util.List;

/**
 * Created by loso on 2017/3/19.
 */
public class _160_IntersectionOfTwoLinkedLists {


    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA==null || headB == null){
            return null;
        }
        int lenA = 0;
        ListNode moveA = headA;
        while(moveA != null){
            lenA++;
            moveA = moveA.next;
        }
        int lenB = 0;
        ListNode moveB = headB;
        while(moveB != null){
            lenB++;
            moveB = moveB.next;
        }
        ListNode temp1 = lenA>=lenB?headA:headB;
        for (int i = 0; i < Math.abs(lenA - lenB); i++) {
            temp1 = temp1.next;
        }
        ListNode temp2 = lenA<lenB?headA:headB;
        while (temp1!=null){
            if (temp1 == temp2){
                return temp1;
            }
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        return null;
    }

}
